<template>
  <div class="service-page">
    <!-- 顶部标题栏 -->
    <div class="header">
      <button class="back-button" @click="goBack">←</button>
      <h1 class="title">完善服务信息</h1>
    </div>

    <!-- 服务特性横幅（固定勾选） -->
    <div class="service-banner">
      <div class="banner-item">
        <div class="fixed-check">✓</div>
        <span>专业师傅</span>
      </div>
      <div class="banner-item">
        <div class="fixed-check">✓</div>
        <span>省心省力</span>
      </div>
      <div class="banner-item">
        <div class="fixed-check">✓</div>
        <span>快速响应</span>
      </div>
    </div>

    <div class="divider"></div>

    <!-- 物品类型 - 使用Vant Picker -->
    <div class="form-section">
      <van-field v-model="itemTypeValue" is-link readonly label="物品类型" placeholder="请选择物品类型" @click="handleTypeClick"
        label-class="required-label" :disabled="loadingTypes || itemTypes.length === 0"
        :clickable="!loadingTypes && itemTypes.length > 0" />
      <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
        <van-picker :model-value="pickerValue" :columns="itemTypes" @cancel="showPicker = false"
          @confirm="onItemTypeConfirm" :loading="loadingTypes" />
      </van-popup>
      <p class="hint">如有多套或不同类型产品的服务需求，可通过购物车功能进行添加~</p>
      <p v-if="loadTypeError" class="error-hint">⚠️ 物品类型加载失败，请点击重试</p>
    </div>

    <div class="divider"></div>

    <!-- 物品图片 - 使用Vant Uploader -->
    <div class="form-section">
      <h2><span class="required">物品图片</span></h2>
      <van-uploader v-model="fileList" multiple :max-count="5" :after-read="afterRead" @delete="deleteImage"
        upload-text="点击上传图片" :preview-size="100" :before-read="beforeRead">
        <template #default>
          <div class="custom-upload-area">
            <van-icon name="plus" size="24" />
            <span>点击上传图片</span>
          </div>
        </template>
      </van-uploader>
    </div>

    <div class="divider"></div>

    <!-- 需求说明 -->
    <div class="form-section">
      <h2>需求说明:</h2>
      <p class="hint">如有特殊需求，可通过留言进行补充说明。</p>
      <p class="example">示例：仅周末有时间，请师傅带齐工具，按时上门。</p>

      <textarea v-model="requirements" placeholder="请输入您的特殊需求..." maxlength="240"></textarea>
      <div class="char-count">{{ requirements.length }}/240</div>
    </div>

    <div class="divider"></div>

    <!-- 加入购物车按钮 -->
    <button class="add-to-cart" @click="addToCart">加入购物车</button>
  </div>
</template>

<script setup name="addgwc">
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Field, Popup, Picker, Uploader, Icon, showToast, showFailToast, showSuccessToast } from 'vant';
import { uploadImageApi } from '../api/index';
import { getFindAllTypes } from '../api/index';
// 导入创建订单的接口
import { getOrderDetails } from '../api/index';
import { useUserInfoStore } from "../stores/userInfo"
import { emitter } from '../utils/eventBus';

const router = useRouter();
const requirements = ref('');
const UserInfoStore = useUserInfoStore();
const userId = ref(1)

const itemTypes = ref([]);
const itemTypeValue = ref('');
const showPicker = ref(false);
const pickerValue = ref([]);
const loadingTypes = ref(true);
const loadTypeError = ref(false);
const selectedTypeId = ref('');

watch(itemTypes, (newVal) => {
  // console.log('物品类型数据更新：', newVal);
  if (newVal.length > 0 && !itemTypeValue.value) {
    // 可选：默认选中第一个类型（根据需求决定是否开启）
    // itemTypeValue.value = newVal[0].text;
    // selectedTypeId.value = newVal[0].value;
    // pickerValue.value = [newVal[0].value];
  }
});

const fetchItemTypes = async () => {
  try {
    loadingTypes.value = true;
    loadTypeError.value = false;
    const response = await getFindAllTypes();

    // console.log('类型接口原始返回：', response);

    const typesData = response.data || response;

    if (Array.isArray(typesData) && typesData.length > 0) {
      itemTypes.value = typesData.map(type => ({
        text: type.categoryName,
        value: type.categoryId,
        raw: type
      }));
      showToast(`成功加载 ${itemTypes.value.length} 种服务类型`);
    } else {
      loadTypeError.value = true;
      showFailToast('未获取到有效服务类型数据');
      console.warn('服务类型数据为空或格式错误');
    }
  } catch (error) {
    loadTypeError.value = true;
    itemTypes.value = [];
    console.error('获取服务类型失败：', error);
    showFailToast('加载服务类型失败，请重试');
  } finally {
    loadingTypes.value = false;
  }
};

onMounted(() => {
  fetchItemTypes();
});

const handleTypeClick = () => {
  console.log('类型选择框点击事件触发，当前状态：', {
    loading: loadingTypes.value,
    hasData: itemTypes.value.length > 0,
    error: loadTypeError.value
  });

  if (loadingTypes.value) {
    showToast('服务类型正在加载，请稍候...');
    return;
  }

  if (loadTypeError.value) {
    showToast('重新尝试加载服务类型...');
    fetchItemTypes();
    return;
  }

  if (itemTypes.value.length > 0) {
    if (selectedTypeId.value) {
      const index = itemTypes.value.findIndex(item => item.value === selectedTypeId.value);
      if (index !== -1) {
        pickerValue.value = [itemTypes.value[index].value];
      }
    }
    showPicker.value = true;
  } else {
    showFailToast('暂无可用的服务类型');
  }
};

const fileList = ref([]);
const uploadedImages = ref([]);

const beforeRead = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    showToast('请上传图片文件');
    return false;
  }

  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    showToast('图片大小不能超过 5MB');
    return false;
  }

  file.status = 'uploading';
  file.message = '上传中...';
  return true;
};

const afterRead = async (file) => {
  try {
    const response = await uploadImageApi(file.file);
    if (response && response.url) {
      file.status = 'done';
      uploadedImages.value.push(response.url);
      showSuccessToast('图片上传成功');
    } else {
      throw new Error('服务器未返回有效图片地址');
    }
  } catch (error) {
    file.status = 'failed';
    file.message = '上传失败';
    showFailToast(`图片上传失败：${error.message}`);
  }
};

const deleteImage = (file, detail) => {
  const index = uploadedImages.value.indexOf(file.url);
  if (index !== -1) {
    uploadedImages.value.splice(index, 1);
  }
};

const onItemTypeConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  if (selectedOptions && selectedOptions.length > 0) {
    const selected = selectedOptions[0];
    itemTypeValue.value = selected.text;
    selectedTypeId.value = selected.value;
    // console.log('选中服务类型：', { 
    //   名称: selected.text, 
    //   ID: selected.value 
    // });
  }
};
const orderDetails = ref(
  {

    "addressId": 1,
    "userId": 1,
    "categoryId": null,
    "serviceId": 3,
    "specialRequirements": "",
    "itemImages": "",

  })
// 加入购物车逻辑，调用创建订单接口
const addToCart = async () => {
  if (!itemTypeValue.value) {
    showToast('请先选择服务类型');
    return;
  }
  if (uploadedImages.value.length === 0) {
    showToast('请上传物品图片');
    return;
  }

  const formData = {
    itemTypeId: selectedTypeId.value,
    itemTypeName: itemTypeValue.value,
    images: uploadedImages.value,
    requirements: requirements.value
  };

  try {
    orderDetails.value.categoryId = formData.itemTypeId
    orderDetails.value.specialRequirements = formData.requirements
    orderDetails.value.itemImages = formData.images[0]
    // 调用创建订单接口
    // console.log("orderDetails.value", orderDetails.value);
    const response = await getOrderDetails(orderDetails.value);
    // console.log('response',response);

    // 假设接口返回 { code: 200, msg: '成功' } 类似格式，可根据实际调整
   
      showSuccessToast('订单创建成功，已加入购物车');
router.push({name:'homepage'})
      // 可选：创建成功后重置表单数据，准备下次填写
      // itemTypeValue.value = '';
      // uploadedImages.value = [];
      // requirements.value = '';
      // selectedTypeId.value = '';
  
    
  } catch (error) {
     showFailToast(`订单创建失败：${response.msg || '未知错误'}`);
    console.error('调用创建订单接口失败：', error);
    showFailToast('网络异常或接口错误，请重试');
  }
};

const goBack = () => {
  router.go(-1);
};
const getuseid = () => {
  if (UserInfoStore.$state.uid) {
    userId.value = UserInfoStore.$state.uid
  }

}

onMounted(() => {
  // console.log();
  getuseid()
  // console.log(userId.value);
  emitter.on('news-service1', (message) => {
    if (message.newsService.serviceId) {
      orderDetails.value.serviceId = message.newsService.serviceId
    }

    //   console.log(message.newsService.serviceId);
    //   console.log('@@');
    //  console.log('rderDetails.value.serviceId',orderDetails.value.serviceId);
    //   console.log('11');

  })

})
</script>

<style scoped>
/* 页面整体样式 */
.service-page {
  max-width: 400px;
  margin: 0 auto;
  height: 100vh;
  background-color: #f5f5f5;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 顶部标题栏样式 */
.header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.back-button {
  font-size: 24px;
  background: none;
  border: none;
  padding: 0 15px;
  cursor: pointer;
  color: #333;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  margin: 0;
  padding-right: 40px;
  font-weight: normal;
}

/* 服务特性横幅样式 */
.service-banner {
  display: flex;
  background-color: #409eff;
  padding: 3px 0;
}

.banner-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.fixed-check {
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 50%;
  color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 14px;
  font-weight: bold;
}

/* 分割线样式 */
.divider {
  height: 1px;
  background-color: #eee;
  margin: 0;
}

/* 表单区块通用样式 */
.form-section {
  font-size: 12px;
  padding: 15px;
  background-color: #fff;
}

.required {
  font-size: 16px;
  margin-right: 5px;
}

.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.hint {
  color: #999;
  font-size: 12px;
  margin: 5px 0 15px;
}

.example {
  color: #409eff;
  font-size: 12px;
  margin: 5px 0 15px;
  font-style: italic;
}

/* 图片上传区域样式 */
:deep(.van-uploader) {
  margin-top: 10px;
}

:deep(.van-uploader__upload) {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 4px;
}

:deep(.van-uploader__preview-image) {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

/* 需求说明文本域样式 */
textarea {
  width: 80%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-family: inherit;
  margin-top: 10px;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 加入购物车按钮样式 */
.add-to-cart {
  width: calc(100% - 30px);
  padding: 12px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  margin: 15px;
  cursor: pointer;
}

.add-to-cart:hover {
  background-color: #e05b5b;
}

/* 自定义上传区域样式 */
:deep(.van-uploader__upload) {
  display: flex !important;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.custom-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}

/* 错误提示样式 */
.error-hint {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  padding: 5px;
  background-color: #fff5f5;
  border-radius: 4px;
}

/* 修复只读字段点击问题 */
:deep(.van-field--readonly) {
  pointer-events: auto !important;
}

:deep(.van-field__control) {
  cursor: pointer;
}
</style>